<template>
  <el-drawer v-model="isVisible" :title="`${'添加' + parentTitle}`" :with-header="true" size="40%" @close="cancelClick">
    <el-form ref="ruleFormRef" :model="formState" label-width="90px" class="demo-ruleForm">
      <el-form-item label="菜单类型:">
        <el-select v-model="formState.menuType" class="el-select-widht">
          <el-option v-for="item in menuTypeListMap" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="菜单名称:">
        <el-input v-model="formState.menuName" placeholder="请输入菜单名称" />
      </el-form-item>
      <el-form-item label="菜单顺序:">
        <el-input v-model="formState.orderNum" placeholder="请输入菜单顺序" />
      </el-form-item>
      <el-form-item label="菜单路径:">
        <el-input v-model="formState.path" placeholder="请输入菜单路径" />
      </el-form-item>
      <el-form-item label="菜单图标:">
        <el-input v-model="formState.icon" placeholder="请输入菜单顺序" />
      </el-form-item>
      <el-form-item label="菜单状态:">
        <el-select v-model="formState.status" class="el-select-widht">
          <el-option v-for="item in menuStateList" :key="item.value" :label="item.label" :value="item.value"
        /></el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from 'vue'
import { addRouter } from '@/api/router'
import { menuStateList, menuTypeListMap } from '../config'

const emit = defineEmits<{
  (e: 'menuAddVisibleClose'): void
  (e: 'menuAddSuccess'): void
}>()

interface Props {
  parentTitle?: string
  pid?: number
  menuAddVisible: boolean
}
const props = withDefaults(defineProps<Props>(), {
  parentTitle: '',
  pid: 0,
  menuAddVisible: true
})
const formState = ref({
  menuName: '', // 菜单名称
  orderNum: '', // 菜单顺序
  icon: '', // 菜单图标
  path: '', // 菜单地址
  menuType: props.parentTitle === '目录' ? 'M' : 'C', // 菜单类型
  status: '1' // 状态
  // parentId: '', // 父级id
  // parentName: '' // 父级名称
})

const isVisible = ref(false)
const parentTitle = ref('')
watch(props, (val) => {
  isVisible.value = val.menuAddVisible
  parentTitle.value = val.parentTitle
})

// 取消
const cancelClick = () => {
  isVisible.value = false
  emit('menuAddVisibleClose')
}
// 确定
const onSubmit = async () => {
  if (formState.value) {
    // 提交
    const res = await addRouter(formState.value)
    if (res.errcode === 0) {
      emit('menuAddSuccess')
      isVisible.value = false
    } else {
      ElMessage.error('添加失败')
      console.log('提交失败', data)
    }
  }
}
</script>
